package javamobile.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mybeans.dao.DAOException;

import javamobile.model.*;

public class RegisterAction extends Action{

	private DAOFactory factory;
	
	public RegisterAction(Model model) {
		factory = model.getDAOFactory();
	}
	
	@Override
	public String getName() {return "register.do";}

	@Override
	public Map<String, Object> perform(Map<String, Object> input) {
		System.out.println("Performing register action!");
		Map<String, Object> output = new HashMap<String, Object>();
		List<String> errors = new ArrayList<String>();
		output.put("errors", errors);
		
		String username = (String) input.get("username");
		String password = (String) input.get("password");
		String firstname = (String) input.get("firstname");
		String lastname = (String) input.get("lastname");
		
		if (username.length() == 0) {
			errors.add("Username is required");
		}
		if (password.length() == 0) {
			errors.add("Password is required");
		}
		if (firstname.length() == 0) {
			errors.add("First name is required");
		}
		if (lastname.length() == 0) {
			errors.add("Last name is required");
		}
		if (errors.size() != 0) {
            return output;
        }
		
		User user = new User(username, password, firstname, lastname);
        try {
        	User lookup = factory.lookupUser(username);
        	if (lookup!=null) {
        		errors.add("User name already exists. Please choose another one.");
        		return output;
        	}
        	user.setUserID(factory.createUser(user));
        } catch (DAOException e) {
        	errors.add(e.getMessage());
        	return output;
        }
		return output;
	}

}
